package com.zhanglifan.service.impl;

import com.zhanglifan.domain.Module;
import com.zhanglifan.domain.Role;
import com.zhanglifan.service.ModuleService;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Set;

/**
 * Information
 * Author: ZhangLifan
 * Time: 2017/9/24 22:22
 * Description: ModuleServiceImpl
 */
public class ModuleServiceImpl extends BaseServiceImpl<Module> implements ModuleService {
    private JedisPool jedisPool;

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Override
    public String getFromRedis(Role role) {

        StringBuilder sb = new StringBuilder();

        Jedis jedis = jedisPool.getResource();

        String jsonStr = jedis.get(role.getId());

        if(jsonStr==null){
            Set<Module> modules = role.getModules();
            List<Module> moduleList = baseDao.find("from Module",Module.class,null);

            StringBuilder sbm = new StringBuilder();

            for (Module m : modules ) {
                sbm.append(m.getName());
                sbm.append(",");
            }
            sb.append("[");
            for (Module m : moduleList) {
                sb.append("{");
                sb.append("\"id\":\"");
                sb.append(m.getId());
                sb.append("\",");
                sb.append("\"pId\":\"");
                sb.append(m.getParentId());
                sb.append("\",");
                sb.append("\"name\":\"");
                sb.append(m.getName());
                sb.append("\",");
                sb.append("\"open\":\"");
                sb.append("true");
                sb.append("\"");

                sb.append(",\"checked\":\"");
                sb.append(sbm.toString().contains(m.getName()));
                sb.append("\"");

                sb.append("},");
            }
            sb.deleteCharAt(sb.lastIndexOf(","));
            sb.append("]");

            jedis.set(role.getId(),sb.toString());
            System.out.println("*** hibernate ***");
        }else{
            sb.append(jsonStr);
            System.out.println("*** redis ***");
        }
        return sb.toString();
    }

    @Override
    public void removeFromRedis(Role role) {
        Jedis jedis = jedisPool.getResource();
        jedis.del(role.getId());
    }
}
